/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;


import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzr.common.utils.OkhttpUtils;
import io.renren.common.exception.BizCodeEnum;
import io.renren.common.exception.RRException;
import io.renren.common.to.wx.Code2SessionTo;
import io.renren.common.utils.JsonUtils;
import io.renren.common.validator.Assert;
import io.renren.common.vo.input.WXLoginVo;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {


    @Value("${wx.code2session.url}")
    private String wxUrl;

    @Autowired
    OkHttpClient client;

    @Override
    public UserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
    }

	@Override
	public UserEntity queryByOpenid(String openid) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("openid", openid));
	}

    @Override
    public long login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }

        return user.getUserId();
    }

    /**
     * wx 登录
     * NOTEME 保证了只有一个入口：必须在WX 服务端验证过后
     * @param param
     * @return
     */
    @Override
    public long wxLogin(WXLoginVo param) throws Exception {
        String url = wxUrl + param.getCode();
        Request requestInJson = OkhttpUtils.getGetRequestInJson(url);
        log.info("request:{}", url);
        Response response = client.newCall(requestInJson).execute();
        String res = response.body().string();
        log.info("response:{}", res);

        String openid = "";
        //如果验证通过
        try {
            Code2SessionTo code2SessionTo = JsonUtils.string2Obj(res, new TypeReference<Code2SessionTo>() {
            });
			openid = code2SessionTo.getOpenid();
            if (openid == null) {
                throw new RRException(BizCodeEnum.WX_NO_USE_EXECUTE.getMsg());
            }
        } catch (Exception e) {
            log.error(res);
            //如果得不到正确的转换
            throw new RRException(BizCodeEnum.WX_LOGIN_EXECUTE.getMsg());
        }

        //如果库内没有用户，进行注册操作
        UserEntity userEntity = queryByOpenid(openid);
        if (userEntity == null) {
            //1.进行注册
            UserEntity entity = new UserEntity(param.getUsername(), openid);
            this.save(entity);
            return entity.getUserId();
        }
        //直接返回

        return userEntity.getUserId();
    }
}
